package com.example.demo.service.impl;

import com.example.demo.service.ResponseCacheService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * ResponseCacheService的实现类，使用Spring Cache实现缓存功能
 */
@Service
public class ResponseCacheServiceImpl implements ResponseCacheService {

    private static final Logger logger = LoggerFactory.getLogger(ResponseCacheServiceImpl.class);
    private static final String CACHE_NAME = "apiResponses";

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public <T> void put(String key, T value, long expireTime, TimeUnit timeUnit) {
        try {
            Cache cache = getCache();
            if (cache != null) {
                // 在实际应用中，这里可以设置过期时间
                // 由于Spring Cache的过期时间通常在配置文件中设置
                // 这里暂时不处理过期时间设置
                cache.put(key, value);
                logger.debug("Cache put: {}", key);
            }
        } catch (Exception e) {
            logger.error("Error putting data into cache: {}", e.getMessage());
        }
    }

    @Override
    public <T> Optional<T> get(String key, Class<T> type) {
        try {
            Cache cache = getCache();
            if (cache != null) {
                Cache.ValueWrapper valueWrapper = cache.get(key);
                if (valueWrapper != null) {
                    Object value = valueWrapper.get();
                    if (type.isInstance(value)) {
                        logger.debug("Cache hit: {}", key);
                        return Optional.of(type.cast(value));
                    } else {
                        // 如果类型不匹配，尝试进行转换
                        // 这部分在实际应用中可能需要更复杂的处理
                        logger.warn("Cache type mismatch for key: {}", key);
                    }
                } else {
                    logger.debug("Cache miss: {}", key);
                }
            }
        } catch (Exception e) {
            logger.error("Error getting data from cache: {}", e.getMessage());
        }
        return Optional.empty();
    }

    @Override
    public void remove(String key) {
        try {
            Cache cache = getCache();
            if (cache != null) {
                cache.evict(key);
                logger.debug("Cache removed: {}", key);
            }
        } catch (Exception e) {
            logger.error("Error removing data from cache: {}", e.getMessage());
        }
    }

    @Override
    public void clear() {
        try {
            Cache cache = getCache();
            if (cache != null) {
                cache.clear();
                logger.debug("Cache cleared");
            }
        } catch (Exception e) {
            logger.error("Error clearing cache: {}", e.getMessage());
        }
    }

    private Cache getCache() {
        return cacheManager.getCache(CACHE_NAME);
    }
}